package top.wshape1.rpc.provider;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import top.wshape1.rpc.provider.handler.ProviderChannelInitializer;

/**
 * @author Wshape1
 * @version 1.0
 * @description 服务提供者
 * @since 2024-02-02
 */

@Slf4j
public class RpcProvider {

    private NioEventLoopGroup bossEventLoopGroup;
    private NioEventLoopGroup workerEventLoopGroup;
    private volatile Channel channel;

    private final int port;


    public RpcProvider(int port) {
        this.port = port;
        initProvider();
    }


    /**
     * 初始化服务提供者
     */
    private void initProvider() {
        log.debug("init provider");
        bossEventLoopGroup = new NioEventLoopGroup();
        workerEventLoopGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        ChannelInitializer<SocketChannel> channelInitializer = new ProviderChannelInitializer();

        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.group(bossEventLoopGroup, workerEventLoopGroup);
        serverBootstrap.childHandler(channelInitializer);
        try {
            channel = serverBootstrap.bind(port).sync().channel();
            channel.closeFuture().addListener(future -> {
                log.debug("provider close");
                bossEventLoopGroup.shutdownGracefully();
                workerEventLoopGroup.shutdownGracefully();
            });
        } catch (Exception e) {
            log.error("init provider error", e);
        }
    }

    /**
     * 停止服务提供者
     */
    public void stop() {
        if (channel != null) {
            // channel 关闭后 bossEventLoopGroup和workerEventLoopGroup随后自动关闭
            channel.close();
        }
    }

}
